package com.work.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;


/**
 * @Author: wanghao
 * @Date: 2019/8/20 10:23
 */
@Configuration
public class RedisConfig {

    @Bean(name = "redisTemplate")
    public RedisTemplate<Object, Object> getRedisTemplate(RedisConnectionFactory redisConnectionFactoryedisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactoryedisConnectionFactory);
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();

        //设置rediskey的序列化方式
        redisTemplate.setKeySerializer(stringSerializer);
        //设置redisvalue的序列化方式
        redisTemplate.setValueSerializer(jsonRedisSerializer);

        //设置redishashkey的序列化方式
        redisTemplate.setHashKeySerializer(stringSerializer);
        //设置redishashvalue的序列化方式
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        return redisTemplate;
    }

    @Bean(name = "myKeyGenerator")
    public KeyGenerator myKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(o.getClass().getName() + ".");
                stringBuilder.append(method.getName() + "(");
                System.out.println(objects.length);
                for (int i = 0; i < objects.length; i++) {
                    stringBuilder.append(objects[i].getClass().getSimpleName() + ":" + objects[i].toString());
                    if (i != objects.length - 1) {
                        stringBuilder.append("&");
                    }
                }
                stringBuilder.append(")");
                return stringBuilder.toString();
            }
        };
    }
}
